<template>
    <div class="form-item">
        <div class="form-item-block">
            <label for="" v-if="label">{{ label }}</label>
            <slot></slot>
        </div>
        <p v-if="error" :class="{ error }">{{ error }}</p>
    </div>
</template>

<script>
import Schema from 'async-validator';
export default {
    inject: ['form'],
    props: {
        label: {
            type: String,
            default: '',
        },
        prop: String,
    },
    data() {
        return {
            error: '',
        };
    },
    methods: {
        validate() {
            const rules = this.form.rules[this.prop];
            const value = this.form.model[this.prop];

            const validator = new Schema({ [this.prop]: rules });
            return validator.validate({ [this.prop]: value }, (errors) => {
                if (errors) {
                    this.error = errors[0].message;
                } else {
                    this.error = '';
                }
            });
        },
    },
    mounted() {
        this.$on('validate', () => this.validate());
    },
};
</script>

<style lang="scss" scoped>
.error {
    color: red;
}
p {
    margin: 0;
}
.form-item {
    margin: 0 0 10px;
    .form-item-block {
        display: flex;
        justify-content: space-between;
    }
}
</style>
